package com.leyou.page.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.dto.BrandDTO;
import com.leyou.dto.CategoryDTO;
import com.leyou.dto.SpecGroupDTO;
import com.leyou.dto.SpuDTO;
import com.leyou.item.client.ItemClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.File;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
public class PageService {
    @Autowired
    private ItemClient itemClient;

    @Autowired
    private SpringTemplateEngine templateEngine;

    public Map<String, Object> loadItemData(Long spuid) {
        //TODO: 判断有没有缓存，如果有直接从缓存中取
        //查询数据集
        SpuDTO spu = itemClient.querySpuById(spuid);
        //查询分类
        List<CategoryDTO> categories = itemClient.queryCategoryByIds(spu.getCategoryIds());
        //查询品牌
        BrandDTO brand = itemClient.queryBrandById(spu.getBrandId());
        //查询规格
        List<SpecGroupDTO> specs = itemClient.querySpecs(spu.getCid3());

        //创建map,存放数据
        Map<String, Object> map = new HashMap<>();
        map.put("categories", categories);
        map.put("brand", brand);
        map.put("spuName", spu.getName());
        map.put("subTitle", spu.getSubTitle());
        map.put("detail", spu.getSpuDetail());
        map.put("skus", spu.getSkus());
        map.put("specs", specs);
    //TODO:将map存入缓存
        return map;
    }

    private static final String HTML_DIR="E:\\nginx-1.12.2\\html\\item";

    public void createItemHtml(Long spuId){
        //1.模板名称
        String template="item";
        //2.上下文
        Context context = new Context();
        context.setVariables(loadItemData(spuId));
        //3.关联一个本地文件
        File file = new File(HTML_DIR, spuId + ".html");
        //4.创建输出流
        try (Writer writer = new PrintWriter(file, "utf-8")) {
            //利用引擎，渲染页面，把页面存入本地文件
            templateEngine.process(template,context,writer);
        }catch (Exception e){
            throw new RuntimeException("创建静态页面失败",e);
        }
    }


    public void deleteItemHtml(Long id) {
        File file = new File(HTML_DIR, id + ".html");
        if(file.exists()){
            if(!file.delete()){
                log.error("静态页删除失败,商品id:{}",id);
                throw new LyException(ExceptionEnum.FILE_WRITER_ERROR);

            }
        }

    }
}
